<template>
  <div class="sticky top-18 mb-1 p-1 grid auto-cols-max grid-flow-col gap-2">
    <Button type="button" label="Add" icon="pi pi-plus" @click="openEditor()" />
    <Button type="button" label="Refresh" icon="pi pi-refresh" @click="getNginxInfos" />
  </div>
  <DataView :value="ngInfos" data-key="id">
    <template #list="slotProps">
      <div class="flex flex-col">
        <div v-for="(item, index) in slotProps.items" :key="index">
          <div
            class="flex flex-col sm:flex-row sm:items-center p-6 gap-4"
            :class="{ 'border-t border-surface-200 dark:border-surface-700': index !== 0 }"
          >
            <div class="flex flex-col md:flex-row justify-between md:items-center flex-1 gap-6">
              <div class="flex flex-row md:flex-col justify-between items-start gap-2">
                <div>
                  <div class="text-lg font-medium mt-2">{{ item.name }}</div>
                </div>
                <div class="bg-surface-100 p-1" style="border-radius: 30px">
                  <div
                    class="bg-surface-0 flex items-center gap-2 justify-center py-1 px-2"
                    style="
                      border-radius: 30px;
                      box-shadow:
                        0 1px 2px 0 rgba(0, 0, 0, 0.04),
                        0 1px 2px 0 rgba(0, 0, 0, 0.06);
                    "
                  >
                    <span class="text-surface-900 font-medium text-sm">{{ item.execPath }}</span>
                  </div>
                </div>
                <div class="bg-surface-100 p-1" style="border-radius: 30px">
                  <div
                    class="bg-surface-0 flex items-center gap-2 justify-center py-1 px-2"
                    style="
                      border-radius: 30px;
                      box-shadow:
                        0 1px 2px 0 rgba(0, 0, 0, 0.04),
                        0 1px 2px 0 rgba(0, 0, 0, 0.06);
                    "
                  >
                    <span class="text-surface-900 font-medium text-sm">{{ item.workDir }}</span>
                  </div>
                </div>
              </div>
              <div class="flex flex-col md:items-end gap-8">
                <span class="text-xl font-semibold">运行状态</span>
                <div class="flex flex-row-reverse md:flex-row gap-2">
                  <Button
                    icon="pi pi-pen-to-square"
                    label="Edit"
                    @click="openEditor(item)"
                    class="flex-auto md:flex-initial whitespace-nowrap"
                  ></Button>
                  <Button
                    icon="pi pi-ellipsis-v" @click="toDetail(item)"
                    class="flex-auto md:flex-initial whitespace-nowrap"
                  ></Button>
                  <Button
                    icon="pi pi-times"
                    severity="danger"
                    outlined
                    @click="deleteConfig($event, item)"
                  ></Button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </DataView>
  <nginx-editor
    v-model:visible="editNgFlag"
    :ng="editingNg"
    @save-config="saveConfig"
  ></nginx-editor>
  <a href="javascript: window.open('https://nginx.org/en/docs/varindex.html')">变量 : https://nginx.org/en/docs/varindex.html</a>
<!--  <Toast />-->
</template>
<script setup lang="ts">
// <p>保存 nginx server 片段， 一个 server 一组， 一组下多个 Location, 一个server 一个 .config 文件， </p>
// <p>操作 nginx , 这里需要知道 nginx -t 返回的是成功还是失败， 需要知道nginx 是否正在运行， 需要知道是应该使用reload 还是使用 start</p>

import type { NginxInfo } from '@/types/dt/Dt.ts'
import { onMounted, ref } from 'vue'
import NginxEditor from '@/views/tools/nginx/nginx-editor.vue'
import type { NginxInfoDto } from '@/views/tools/nginx/nginx-info.ts'
import { useToast } from 'primevue/usetoast'
import { useConfirm } from 'primevue/useconfirm'
import { useRouter } from 'vue-router'

const router = useRouter()
const current = router.currentRoute.value.fullPath + ''
// 添加弹窗显示
const editNgFlag = ref(false)
// toast service
const toast = useToast()
// confirm service
const confirm = useConfirm()
// 正在编辑的 ID
const editingNg = ref<NginxInfo>()
// 删除
const deleteConfig = (e: MouseEvent, data: NginxInfo) => {
  confirm.require({
    target: e.currentTarget as HTMLElement,
    message: 'Are you sure you want to delete?',
    icon: 'pi pi-exclamation-triangle',
    rejectProps: {
      label: 'Cancel',
      severity: 'secondary',
      outlined: true,
    },
    acceptProps: {
      label: 'Delete',
      severity: 'danger',
    },
    accept: async () => {
      await window.DefaultDt.delNginxInfo(data.id!)
      getNginxInfos()
    },
  })
}

// 查询信息
const ngInfos = ref<NginxInfo[]>([])
const getNginxInfos: () => Promise<NginxInfo[]> = async () => {
  try {
    const infos = await window.DefaultDt.getNginxInfo()
    ngInfos.value = infos || []
    return ngInfos.value
  } catch (err) {
    console.log(err)
    return []
  }
}

const openEditor = (n?: NginxInfo) => {
  editingNg.value = n
  editNgFlag.value = true
}

// 保存信息
const saveConfig = async (v: NginxInfoDto) => {
  try {
    const r = await window.DefaultDt.saveNginxInfo(v)
    if (r.code === 1) {
      toast.add({
        severity: 'success',
        summary: 'Success',
      })
      getNginxInfos()
      editNgFlag.value = false
    } else {
      toast.add({
        severity: 'error',
        summary: 'Failed to save nginxInfo',
        detail: r.msg,
      })
    }
  } catch (e: any) {
    toast.add({
      severity: 'error',
      summary: 'save info error',
      detail: e.message,
    })
  }
}

const toDetail = (ng: NginxInfo) => {
  router.push({
    path: current + "/config-detail",
    query: {
      id: ng.id
    }
  })

}

onMounted(() => {
  getNginxInfos()
})
</script>
<style scoped lang="scss"></style>
